package com.xw.kotlinlib.app

import android.app.Activity
import java.util.*

class ActivityStack {

    private val stack by lazy { Stack<Activity>() }

    companion object {
        fun getInstance(): ActivityStack {
            return ActivityStack()
        }
    }

    /**
     * 获取管理栈实例对象.
     *
     * @return 管理栈实例
     */
    open

    /**
     * 向栈中添加一个activity实例.
     *
     * @param activity 需要添加的activity
     */
    fun add(activity: Activity) {
        stack.push(activity)
    }

    /**
     * 将一个activity从管理栈中移除出去
     *
     * @param activity 需要移除的管理栈
     */
    fun remove(activity: Activity) {
        stack.remove(activity)
    }

    /**
     * 获取管理栈中所有的activity, 每次调用返回的都是一个新的集合对象
     *
     * @return 栈内的activity集合
     */
    fun getActivity(): List<Activity?> {
        return ArrayList(stack)
    }

    /**
     * 关闭指定类型的activity.
     *
     * @param clazz activity 类型
     */
    fun finish(clazz: Class<out Activity?>) {
        val finishList: MutableList<Activity> = ArrayList()
        for (activity in stack) {
            if (activity.javaClass == clazz) {
                finishList.add(activity)
            }
        }
        for (activity in finishList) {
            stack.remove(activity)
            activity.finish()
        }
    }

    /**
     * 关闭所有activity
     */
    fun finishAll() {
        for (activity in stack) {
            activity.finish()
        }
        stack.clear()
    }
}